using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NorthwindWeb.Models;

namespace NorthwindWeb.Controllers
{   
    public class RegionController : Controller
    {
		private readonly IRegionRepository regionRepository;

		// If you are using Dependency Injection, you can delete the following constructor
        public RegionController() : this(new RegionRepository())
        {
        }

        public RegionController(IRegionRepository regionRepository)
        {
			this.regionRepository = regionRepository;
        }

        //
        // GET: /Region/

        public ViewResult Index()
        {
            return View(regionRepository.AllIncluding(region => region.Territories));
        }

        //
        // POST: /Region/Create

        [HttpPost]
        public ActionResult Create([Bind(Exclude = "RegionID")]Region region)
        {
            if (ModelState.IsValid) {
                regionRepository.InsertOrUpdate(region);
                regionRepository.Save();
                return RedirectToAction("Index");
            } else {
                return RedirectToAction("Index");
            }
        }

        //
        // POST: /Region/Edit/5

        [HttpPost]
        public ActionResult Edit(Region region)
        {
            if (ModelState.IsValid) {
                regionRepository.InsertOrUpdate(region);
                regionRepository.Save();
                return RedirectToAction("Index");
            } else {
                return RedirectToAction("Index");
            }
        }

        //
        // POST: /Region/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            regionRepository.Delete(id);
            regionRepository.Save();

            return RedirectToAction("Index");
        }

        
        public JsonResult regionGridData(int rows, int page)
        {
        	var count = regionRepository.All.Count();
            var pageData = regionRepository.All.OrderBy(x => x.RegionID).Skip((page - 1) * rows).Take(rows).Select(o => new {RegionID = o.RegionID, RegionDescription = o.RegionDescription});
            return Json(new { 
            page = page,
            records = count,
            rows = pageData,
            total = Math.Ceiling((decimal)count / rows)
            }, JsonRequestBehavior.AllowGet);
        }
        
        
    }
}

